<template>
  <view class="editinfo-container">
    <view class="title">修改信息</view>
    <view class="User">
	<input v-model="User.userId" placeholder="用户名" class="input" disabled />
      <input v-model="User.username" placeholder="用户名" class="input" disabled />
      <input v-model="User.realName" placeholder="真实姓名" class="input" />
      <picker :range="genderOptions" @change="onGenderChange">
        <view class="picker">
          性别：{{ genderOptions[User.gender] || '请选择' }}
        </view>
      </picker>
      <input v-model="User.phone" placeholder="手机号" class="input" />
      <input v-model="User.email" placeholder="邮箱" class="input" />
      <input v-model="User.avatar" placeholder="头像地址" class="input" />
      <button class="update-btn" @click="onUpdate">修改信息</button>
    </view>
    <view v-if="msg" class="msg">{{ msg }}</view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const UserList = uni.getStorageSync('userList')

const User = ref({
userId: UserList.userId,
  username: UserList.username,
  realName: UserList.realName,
  gender: UserList.gender,
  phone: UserList.phone,
  email: UserList.email,
  avatar: UserList.avatar,
})

const genderOptions = ['男', '女']
const msg = ref('')

// 页面加载时获取用户信息
onMounted(() => {
  const storedUserList = uni.getStorageSync('userList') || []
  if (storedUserList.length > 0) {
    User.value = { ...storedUserList[0] }
    // 性别转换为数组索引
    if (User.value.gender) {
      User.value.gender -= 1
    }
  }
})

function onGenderChange(e) {
  User.value.gender = e.detail.value
}

function validate() {
  // 手机号校验（中国大陆手机号）
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(User.value.phone)) {
    uni.showToast({ title: '手机号格式错误', icon: 'none' });
    return false;
  }
  // 邮箱校验
  const emailReg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
  if (!emailReg.test(User.value.email)) {
    uni.showToast({ title: '邮箱格式错误', icon: 'none' });
    return false;
  }
  return true;
}

function onUpdate() {
  if (!validate()) return; // 校验不通过直接返回

  // 性别转换为后端需要的格式
  const userData = { ...User.value }
  if (userData.gender !== null) {
    userData.gender = userData.gender + 1
  }

  uni.request({
    url: '/api/user/update',
    method: 'POST',
    data: userData,
    success: (res) => {
      if (res.data.code == 0) {
        uni.showToast({
          title: '修改信息成功',
          icon: 'success',
          duration: 1000
        });
        // 将后端返回的新用户信息保存到本地 userList 中
        if (res.data.data) {
          const newUserInfo = res.data.data;
          let userList = uni.getStorageSync('userList') || [];
          userList[0] = newUserInfo;
          uni.setStorageSync('userList', userList);
          // 更新当前页面的用户信息
          User.value = {
            ...newUserInfo,
            gender: newUserInfo.gender ? newUserInfo.gender - 1 : null
          };
        }
        setTimeout(() => {
          // 修改跳转逻辑，跳转到登录页面
          uni.navigateTo({ url: '/pages/login/login' });
        }, 2000);
      } else {
        msg.value = res.data.message || '修改信息失败'
      }
    },
    fail: () => {
      msg.value = '修改信息失败'
    }
  })
}
</script>

<style scoped>
.editinfo-container {
  min-height: 100vh;
  background: #f7f7f7;
  padding: 40rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}
.User {
  width: 100%;
  max-width: 500rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.06);
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  gap: 18rpx;
}
.input {
  height: 48rpx;
  border-radius: 8rpx;
  border: 1rpx solid #eee;
  font-size: 28rpx;
  padding: 0 16rpx;
  background: #f4f4f4;
}
.picker {
  height: 48rpx;
  line-height: 48rpx;
  border-radius: 8rpx;
  border: 1rpx solid #eee;
  font-size: 28rpx;
  padding: 0 16rpx;
  background: #f4f4f4;
  color: #666;
}
.update-btn {
  height: 54rpx;
  background: #2B9939;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 30rpx;
  margin-top: 18rpx;
}
.msg {
  margin-top: 30rpx;
  font-size: 28rpx;
  color: #e53935;
}
</style>